package com.demo.security.controller;

import com.demo.common.Result;
import com.demo.controller.BaseController;
import com.demo.ex.UsernameIsExitedException;
import com.demo.security.model.SysUser;
import com.demo.security.service.JwtUserService;
import com.demo.security.service.UserService;
import com.demo.security.util.JwtTokenUtil;
import com.demo.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "用户")
@RestController
@RequestMapping("user")
public class UserController extends BaseController {
    @Autowired
    UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserService jwtUserService;




//    /**
//     * 验证用户名和密码。
//     * 如果验证通过，创建token并将其返回给客户端
//     *
//     * @param request
//     * @return
//     */
//    @ApiOperation(value = "获取token", notes = "获取token")
//    @PostMapping(value = "/auth")
//    public ResponseEntity<?> createAuthenticationToken(@ApiParam(name = "sysUser",value = "用户参数") @RequestBody SysUser sysUser,
//                                                       HttpServletRequest request,
//                                                       HttpServletResponse response) {
//        String username = sysUser.getName();
//        String password = sysUser.getPassword();
//        System.out.println("用户名:" + username);
//        System.out.println("密码:" + password);
//
//        UsernamePasswordAuthenticationToken authentication=new UsernamePasswordAuthenticationToken(username, password);
//        Authentication authenticate = authenticationManager.authenticate(authentication);
//        UserDetails userDetails = jwtInMemoryUserDetailsService.loadUserByUsername(sysUser.getName());
//        String token = jwtTokenUtil.generateToken(userDetails);
//        response.setHeader("Authorization","Bearer "+token);
//        JwtResponse jwtResponse =  new JwtResponse(token);
//        return ResponseEntity.ok("Authorization: "+ "Bearer "+token);
//    }

    /**
     * 获取登录用户
     * @return
     */
    @GetMapping("loginUser")
    public SysUser getLoginUser(){
       return UserUtil.getSysUser();
    }

    @PostMapping("/getUser")
    public String getUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        boolean authenticated = authentication.isAuthenticated();
        log.info("authenticated:" + authenticated);
        log.info("author:"+authentication.getAuthorities());
        log.info("getCredentials:"+authentication.getCredentials());
        log.info("getCredentials:"+authentication.getDetails());
        return "00";
    }

    @PreAuthorize("hasAuthority('user:resource1')")
    @GetMapping("/getResource")
    public String getResource(){
        return "资源";
    }


    /**
     * 注册用户 默认开启白名单
     * @param sysUser
     */
    @PostMapping("/signup")
    public SysUser signup(@RequestBody SysUser sysUser) {
        SysUser bizUser = userService.getUserByName (sysUser.getUsername());
        if(null != bizUser){
            throw new UsernameIsExitedException("用户已经存在");
        }
        /*user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()).getBytes()));*/
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
         userService.save(sysUser);
         return sysUser;
    }

    /**
     * 获取用户列表
     * @return
     */
    @ApiModelProperty(value = "获取用户列表")
    @GetMapping("/userList")
    public Map<String, Object> userList(){
        List<SysUser> users = userService.getUser();
        logger.info("sysUser: {}", users);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysUser",users);
        return map;
    }

    /**
     * 获取用户权限
     * @return
     */
    @ApiModelProperty(value = "获取用户权限")
    @GetMapping("/authorityList")
    public List<String> authorityList(){
        List<String> authentication = getAuthentication();
        return authentication;
    }



}
